'use strict';

/**
 * 登录账户逻辑控制器
 */
const Code = require('../common/error_code');
const Cons = require('../common/constants');
const customModel = require('../models/customview.model');
const UserModel = require('../models/user.model');
const Util = require('../utils/hobot_util');
const Config = require('../controllers/config');
const mongoose = require('mongoose');
const logger = require('../utils/logger');

async function query_logo(ctx) {
    let logo = await Config.getLogoConfig();
    if (logo && logo.data && logo.type) {
        ctx.success(Code.RET_QUERY_LOGO_SUCCESS,
            logo);
    } else {
        ctx.error(Code.RET_QUERY_LOGO_ERR_NOT_EXISTS);
    }
}

async function query_users_show(ctx) {
    let show = await Config.getUsersShow();
    if (show) {
        ctx.success(Code.RET_QUERY_USERS_SHOW_SUCCESS, show);
    } else {
        ctx.error(Code.RET_QUERY_USERS_SHOW_ERR_NOT_EXISTS);
    }
}

async function replace_text(user, text) {
    if (text != undefined && text.length != 0) {
        let name = "";
        let department = "";
        let company = "";
        let id = "";
        if (user != undefined) {
            if (user.u_nm != undefined) {
                name = user.u_nm;
            }
            const dms = await Config.getDeptList();
            console.log(dms);
            if (user.u_dm != undefined) {
                for (let i = 0; i < dms.length; ++i) {
                    if (dms[i].value == user.u_dm) {
                        department = dms[i].label;
                        break;
                    }
                }
            }
            if (user.g_cp != undefined) {
                company = user.g_cp;
            }
            if (user.u_no != undefined) {
                id = user.u_no;
            }
        }
        let re = new RegExp("\\$\\{" + Cons.REPLACE_TIME + "\\}", "g");
        let date = new Date();
        let timestr = date.getHours().toString() + ':' + date.getMinutes().toString();
        text = text.replace(re, timestr);
        re = new RegExp("\\$\\{" + Cons.REPLACE_NAME + "\\}", "g");
        text = text.replace(re, name);
        re = new RegExp("\\$\\{" + Cons.REPLACE_DEPARTMENT + "\\}", "g");
        text = text.replace(re, department);
        re = new RegExp("\\$\\{" + Cons.REPLACE_COMPANY + "\\}", "g");
        text = text.replace(re, company);
        re = new RegExp("\\$\\{" + Cons.REPLACE_ID + "\\}", "g");
        text = text.replace(re, id);
    }
    return text;
}

async function query_custom_detail(ctx) {
    let params = ctx.request.query;

    let opts = {};
    // if (params.user_type !== undefined && (params.user_type != Cons.USER_TYPE_GUEST
    //     || params.user_type != Cons.USER_TYPE_STAFF
    //     || params.user_type != Cons.USER_TYPE_TRAINEE
    //     || params.user_type != Cons.USER_TYPE_VIP)) {
    //     return ctx.error(Code.RET_CUSTOM_QUERY_ERR_PARAMS);
    // }
    // if (params.custom_type !== undefined && (params.custom_type != Cons.CUSTOM_VIEW_TYPE_DYNAMIC
    //     || params.custom_type != Cons.CUSTOM_VIEW_TYPE_STATIC)) {
    //     return ctx.error(Code.RET_CUSTOM_QUERY_ERR_PARAMS);
    // }
    if (params.user_type !== undefined) {
        opts.user_type = params.user_type;
    }

    if (params.custom_type !== undefined) {
        opts.custom_type = params.custom_type;
    }
    let customs = await customModel.find(opts);
    ctx.success(Code.RET_CUSTOM_QUERY_SUCCESS, customs);
}

async function query_custom_detail_app(ctx) {
    let params = ctx.request.query;

    let opts = {};
    if (params.user_type !== undefined) {
        opts.user_type = params.user_type;
    }

    if (params.custom_type !== undefined) {
        opts.custom_type = params.custom_type;
    }
    let user = undefined;
    if (params.user_id != undefined) {
        user = await UserModel.findOne({_id: params.user_id.toString()});
    }
    let customs = await customModel.find(opts);
    for (let i in customs) {
        const custom = customs[i];
        custom.title = await replace_text(user, custom.title);
        custom.body = await replace_text(user, custom.body);
        custom.voice_text = await replace_text(user, custom.voice_text);
    }
    logger.logInfo("\n" + '===== query_custom_detail - ' +
        JSON.stringify(customs) + "\n");
    ctx.success(Code.RET_CUSTOM_QUERY_SUCCESS, customs);
}

function getTime(timestr /* HHmm */) {
    let h = timestr.slice(0, 2);
    let m = timestr.slice(2);
    return h * 60 + m;
}

function isConflict(cs, ct, s, t) {
    if (s >= ct)
        return false;
    if (cs >= t)
        return false;
    return true;
}

async function add(ctx) {
    let params = ctx.request.body;

    if (params.custom_type == undefined
        || params.user_type == undefined
        || params.bgcolor == undefined
        || params.title == undefined
        || params.body == undefined
        || params.name == undefined
        || params.stay == undefined
        || params.voice_type == undefined
    ) {
        return ctx.error(Code.RET_CUSTOM_ADD_ERR_PARAM);
    }
    if (params.custom_type == Cons.CUSTOM_VIEW_TYPE_DYNAMIC
        && (params.start_time == undefined || params.end_time == undefined)) {
        return ctx.error(Code.RET_CUSTOM_ADD_ERR_PARAM);
    }
    if (params.voice_type < 0 || params.voice_type > 2) {
        return ctx.error(Code.RET_CUSTOM_ADD_ERR_PARAM);
    }
    if (params.stay < 0 || params.stay > 600) {
        return ctx.error(Code.RET_CUSTOM_ADD_ERR_PARAM);
    }

    if (params.custom_type == Cons.CUSTOM_VIEW_TYPE_DYNAMIC) {
        let customs = await customModel.find({
            user_type: params.user_type,
            custom_type: Cons.CUSTOM_VIEW_TYPE_DYNAMIC
        });
        let conflict = false;
        let cstart = getTime(params.start_time);
        let cstop = getTime(params.end_time);
        customs.map((custom) => {
            let start = getTime(custom.start_time);
            let stop = getTime(custom.end_time);

            conflict = conflict || isConflict(cstart, cstop, start, stop);
        });
        if (conflict) {
            return ctx.error(Code.RET_CUSTOM_ADD_ERR_CONFLICT);
        }
    } else {
        let customs = await customModel.find({
            user_type: params.user_type,
            custom_type: Cons.CUSTOM_VIEW_TYPE_STATIC
        });

        if (customs.length > 0) {
            let custom = customs[0];
            return await updateInternal(ctx, custom._id, params);
        }
    }
    params._id = new mongoose.Types.ObjectId();
    await customModel.create(params);
    ctx.success(Code.RET_CUSTOM_ADD_SUCCESS);

}

async function updateInternal(ctx, custom_id, params) {
    if (params.custom_type == Cons.CUSTOM_VIEW_TYPE_DYNAMIC) {
        let customs = await customModel.find({
            user_type: params.user_type,
            custom_type: Cons.CUSTOM_VIEW_TYPE_DYNAMIC
        });
        let conflict = false;
        let cstart = getTime(params.start_time);
        let cstop = getTime(params.end_time);
        customs.map((custom) => {
            if (custom._id == custom_id)
                return;
            let start = getTime(custom.start_time);
            let stop = getTime(custom.end_time);

            conflict = conflict || isConflict(cstart, cstop, start, stop);
        });
        if (conflict) {
            return ctx.error(Code.RET_CUSTOM_UPDATE_ERR_CONFLICT);
        }
    }
    const opts = {
        _id: custom_id
    }
    const custom = await customModel.findOne(opts);
    if (!custom) {
        return ctx.error(Code.RET_CUSTOM_UPDATE_ERR_NOT_EXISTS);
    }
    const cdt = { _id: custom_id };
    const model = {
        start_time: params.start_time,
        end_time: params.end_time,
        bgcolor: params.bgcolor,
        name: params.name,
        title: params.title,
        body: params.body,
        stay: params.stay,
        voice_type: params.voice_type,
        voice_text: params.voice_text
    };
    await customModel.update(cdt, model);
    ctx.success(Code.RET_CUSTOM_UPDATE_OK);
}

async function update(ctx) {
    let params = ctx.request.body;
    let custom_id = params.custom_id;
    return await updateInternal(ctx, custom_id, params);
}

async function del(ctx) {
    let params = ctx.request.body;
    if (!params.custom_id) {
        return ctx.error(Code.RET_CUSTOM_DELETE_ERR_PARAM);
    }

    const opts = {
        _id: params.custom_id
    }
    const custom = await customModel.findOne(opts);
    if (!custom) {
        return ctx.error(Code.RET_CUSTOM_DELETE_ERR_NOT_EXIST);
    }

    await customModel.remove(opts);

    ctx.success(Code.RET_CUSTOM_DELETE_SUCCESS);
}

async function clean(ctx) {
    await customModel.remove();
    ctx.success(Code.RET_CUSTOM_CLEAN_SUCCESS);
}

exports.del = del;
exports.add = add;
exports.update = update;
exports.query_logo = query_logo;
exports.query_users_show = query_users_show;
exports.query_custom_detail = query_custom_detail;
exports.query_custom_detail_app = query_custom_detail_app;

exports.clean = clean;


